//
//  Tool_y.swift
//  Library_y
//
//  Created by JC on 2023/6/6.
//

import Foundation
import UIKit

public struct Tools { }

extension Tools {
    
    /// 获取当前显示的控制器
    static public func currentViewController() -> UIViewController {
        let vc = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController
        return Tools.findBestViewController(vc: vc!)
    }
    
    static public func findBestViewController(vc : UIViewController) -> UIViewController {
        if vc.presentedViewController != nil {
            return Tools.findBestViewController(vc: vc.presentedViewController!)
        } else if vc.isKind(of:UISplitViewController.self) {
            let svc = vc as! UISplitViewController
            if svc.viewControllers.count > 0 {
                return Tools.findBestViewController(vc: svc.viewControllers.last!)
            } else {
                return vc
            }
        } else if vc.isKind(of: UINavigationController.self) {
            let nvc = vc as! UINavigationController
            if nvc.viewControllers.count > 0 {
                return Tools.findBestViewController(vc: nvc.topViewController!)
            } else {
                return vc
            }
        } else if vc.isKind(of: UITabBarController.self) {
            let tvc = vc as! UITabBarController
            if (tvc.viewControllers?.count)! > 0 {
                return Tools.findBestViewController(vc: tvc.selectedViewController!)
            } else {
                return vc
            }
        } else {
            return vc
        }
    }
    
    // 比较指定ViewController是否显示在屏幕上
    static public func isCurrentViewControllerVisible(clzz: UIViewController.Type) -> Bool{
        let viewController = Tools.currentViewController()
        if viewController.isMember(of: clzz) { return true }
        return false
    }
}

extension Tools {
    
    /// data转字符串
    static public func data2Str(_ data: Data) -> String {
        let bytes = [UInt8](data)
        var str = ""
        for i in bytes {
            str += String(format: "%02X", arguments: [i])
        }
        return str
    }
    
    /// 字节转字符串
    static public func bytes2Str(_ bytes: [UInt8]) -> String {
        var str = ""
        for i in bytes {
            str += String(format: "%02X", arguments: [i])
        }
        return str
    }
    
    // 字节转SN
    static public func bytes2SN(_ bytes: [UInt8]) -> String {
        var str = ""
        for i in 0 ..< bytes.count {
            if i < 9 {
                str += String(format: "%C", arguments: [bytes[i]])
            } else {
                str += String(format: "%02X", arguments: [bytes[i]])
            }
        }
        return str
    }
    
    // MARK: -  十六进制字符串转UInt8数组
    static public func hexToBytes(_ hexStr: String) -> [UInt8] {
        var bytes = [UInt8]()
        var sum = 0
        // 整形的 utf8 编码范围
        let intRange = 48...57
        // 小写 a~f 的 utf8 的编码范围
        let lowercaseRange = 97...102
        // 大写 A~F 的 utf8 的编码范围
        let uppercasedRange = 65...70
        for (index, c) in hexStr.utf8CString.enumerated() {
            var intC = Int(c.byteSwapped)
            if intC == 0 {
                break
            } else if intRange.contains(intC) {
                intC -= 48
            } else if lowercaseRange.contains(intC) {
                intC -= 87
            } else if uppercasedRange.contains(intC) {
                intC -= 55
            } else {
                assertionFailure("输入字符串格式不对，每个字符都需要在0~9，a~f，A~F内")
            }
            sum = sum * 16 + intC
            // 每两个十六进制字母代表8位，即一个字节
            if index % 2 != 0 {
                bytes.append(UInt8(sum))
                sum = 0
            }
        }
        return bytes
    }
    
    // MARK: - 字符串转UInt8数组, 例：602 --->>> [2, 0, 6]
    static public func bcd2u8(_ str: String) -> [UInt8] {
        guard let data = str.data(using: .utf8) else { return [UInt8]() }
        let bytes = Array(data)
        var u8s = Array<UInt8>(repeating: 0, count: bytes.count)
        for i in 0 ..< bytes.count { u8s[i] = bytes[i] - 48 }
        return u8s
    }
    
    /// 获取16进制中有效字符串
    /// - Parameter hexStr: 16进制
    /// - Returns: 字符串
    static public func getAvailableText(_ hexStr: String) -> String {
        var _text = hexStr
        while(true) {
            let bytes = Tools.hexToBytes(_text)
            let str = String(bytes: bytes, encoding: .utf8) ?? ""
            if str.isEmpty {
                _text.removeLast()
            } else {
                _text = str
                break
            }
        }
        return _text
    }
}

extension Tools {
    
    // 手机号码正则表达式
    static public func isTelNumber(num: NSString) -> Bool {
        let mobile = "^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$"
        let CM = "^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$"
        let CU = "^1(3[0-2]|5[256]|8[56])\\d{8}$"
        let CT = "^1((33|53|8[09])[0-9]|349)\\d{7}$"
        let regextestmobile = NSPredicate(format: "SELF MATCHES %@",mobile)
        let regextestcm = NSPredicate(format: "SELF MATCHES %@",CM )
        let regextestcu = NSPredicate(format: "SELF MATCHES %@" ,CU)
        let regextestct = NSPredicate(format: "SELF MATCHES %@" ,CT)
        if ((regextestmobile.evaluate(with: num) == true)
            || (regextestcm.evaluate(with: num)  == true)
            || (regextestct.evaluate(with: num) == true)
            || (regextestcu.evaluate(with: num) == true)) {
            return true
        } else {
            return false
        }
    }
}

extension Tools {
    
    // 随机数的生成
    static public func randomCustom(min: Int, max: Int) -> Int {
        let y = arc4random() % UInt32(max) + UInt32(min)
        return Int(y)
    }
}

